<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
                  <el-form-item label="用户ID" prop="userId">
                    <el-input v-model="queryParams.userId" placeholder="请输入用户ID" clearable @keyup.enter.native="handleQuery"/>
                  </el-form-item>
<!--                  <el-form-item label="现有部门ID" prop="currentDeptId">-->
<!--                    <el-input v-model="queryParams.currentDeptId" placeholder="请输入现有部门ID" clearable @keyup.enter.native="handleQuery"/>-->
<!--                  </el-form-item>-->
                  <el-form-item label="现有部门名称" prop="currentDeptName">
                    <el-input v-model="queryParams.currentDeptName" placeholder="请输入现有部门名称" clearable @keyup.enter.native="handleQuery"/>
                  </el-form-item>
<!--                  <el-form-item label="目标部门ID" prop="targetDeptId">-->
<!--                    <el-input v-model="queryParams.targetDeptId" placeholder="请输入目标部门ID" clearable @keyup.enter.native="handleQuery"/>-->
<!--                  </el-form-item>-->
                  <el-form-item label="目标部门名称" prop="targetDeptName">
                    <el-input v-model="queryParams.targetDeptName" placeholder="请输入目标部门名称" clearable @keyup.enter.native="handleQuery"/>
                  </el-form-item>
                  <el-form-item label="申请时间" prop="applyTime">
                    <el-date-picker clearable v-model="queryParams.applyTime" type="date" value-format="yyyy-MM-dd" placeholder="请选择申请时间"></el-date-picker>
                  </el-form-item>
                  <el-form-item label="审批时间" prop="approvalTime">
                    <el-date-picker clearable v-model="queryParams.approvalTime" type="date" value-format="yyyy-MM-dd" placeholder="请选择审批时间"></el-date-picker>
                  </el-form-item>
                  <el-form-item label="审批人ID" prop="approverId">
                    <el-input v-model="queryParams.approverId" placeholder="请输入审批人ID" clearable @keyup.enter.native="handleQuery"/>
                  </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['system:apply:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['system:apply:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:apply:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['system:apply:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="applyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="id" align="center" prop="id" />
              <el-table-column label="申请人" align="center" prop="createBy" />
<!--              <el-table-column label="现有部门ID" align="center" prop="currentDeptId" />-->
              <el-table-column label="现部门" align="center" prop="currentDeptName" />
<!--              <el-table-column label="目标部门ID" align="center" prop="targetDeptId" />-->
              <el-table-column label="目标部门" align="center" prop="targetDeptName" />
              <el-table-column label="申请原因" align="center" prop="applyReason" />
              <el-table-column prop="applyTime" label="申请时间" min-width="180" align="center">
                  <template slot-scope="scope">
                      {{ formatDateTime(scope.row.applyTime) }}
                  </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                  <template slot-scope="scope">
                    <el-tooltip
                      v-if="scope.row.status === 3"
                      :content="scope.row.reasonsRejection || '暂无驳回原因'"
                      placement="top"
                      effect="dark"
                    >
                      <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
                    </el-tooltip>
                    <el-tag v-else :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
                  </template>
              </el-table-column>
<!--              <el-table-column label="驳回原因" align="center" prop="reasonsRejection" />-->

              <el-table-column label="审批时间" align="center" prop="approvalTime" width="180">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.approvalTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="审批人" align="center" prop="approverName" />

        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
                <template v-if="scope.row.status === 1">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row,2)" v-hasPermi="['system:apply:edit']">通过</el-button>
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row,3)" v-hasPermi="['system:apply:edit']">驳回</el-button>
                </template>
                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['system:apply:remove']">删除记录</el-button>
            </template>
        </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>

    <!-- 添加或修改申请更换部门审批对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                        <el-form-item label="用户ID" prop="userId">
                          <el-input v-model="form.userId" placeholder="请输入用户ID" />
                        </el-form-item>
                        <el-form-item label="现有部门ID" prop="currentDeptId">
                          <el-input v-model="form.currentDeptId" placeholder="请输入现有部门ID" />
                        </el-form-item>
                        <el-form-item label="现有部门名称" prop="currentDeptName">
                          <el-input v-model="form.currentDeptName" placeholder="请输入现有部门名称" />
                        </el-form-item>
                        <el-form-item label="目标部门ID" prop="targetDeptId">
                          <el-input v-model="form.targetDeptId" placeholder="请输入目标部门ID" />
                        </el-form-item>
                        <el-form-item label="目标部门名称" prop="targetDeptName">
                          <el-input v-model="form.targetDeptName" placeholder="请输入目标部门名称" />
                        </el-form-item>
                        <el-form-item label="申请时间" prop="applyTime">
                          <el-date-picker clearable
                                          v-model="form.applyTime"
                                          type="date"
                                          value-format="yyyy-MM-dd"
                                          placeholder="请选择申请时间">
                          </el-date-picker>
                        </el-form-item>
                        <el-form-item label="审批时间" prop="approvalTime">
                          <el-date-picker clearable
                                          v-model="form.approvalTime"
                                          type="date"
                                          value-format="yyyy-MM-dd"
                                          placeholder="请选择审批时间">
                          </el-date-picker>
                        </el-form-item>
                        <el-form-item label="审批人ID" prop="approverId">
                          <el-input v-model="form.approverId" placeholder="请输入审批人ID" />
                        </el-form-item>
                        <el-form-item label="申请原因" prop="applyReason">
                          <el-input v-model="form.applyReason" type="textarea" placeholder="请输入内容" />
                        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { listApply, getApply, delApply, addApply, updateApply } from "@/api/system/apply";
  import {copyObj} from "@/utils/zzDouUtils/objUtil";

  export default {
    name: "Apply",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 申请更换部门审批表格数据
              applyList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
                        userId: null,
                        currentDeptId: null,
                        currentDeptName: null,
                        targetDeptId: null,
                        targetDeptName: null,
                        applyTime: null,
                        approvalTime: null,
                        approverId: null,
                        status: null,
                        applyReason: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
                        userId: [
                    { required: true, message: "用户ID不能为空", trigger: "blur" }
                  ],
                        currentDeptId: [
                    { required: true, message: "现有部门ID不能为空", trigger: "blur" }
                  ],
                        currentDeptName: [
                    { required: true, message: "现有部门名称不能为空", trigger: "blur" }
                  ],
                        targetDeptId: [
                    { required: true, message: "目标部门ID不能为空", trigger: "blur" }
                  ],
                        targetDeptName: [
                    { required: true, message: "目标部门名称不能为空", trigger: "blur" }
                  ],
                        applyTime: [
                    { required: true, message: "申请时间不能为空", trigger: "blur" }
                  ],
                        status: [
                    { required: true, message: "状态不能为空", trigger: "change" }
                  ],
                        applyReason: [
                    { required: true, message: "申请原因不能为空", trigger: "blur" }
                  ],
        }
      };
    },
    created() {
      this.getList();
    },
    methods: {
      /** 格式化日期时间 */
      formatDateTime(date) {
        if (!date) return '';
        const d = new Date(date);
        const year = d.getFullYear();
        const month = d.getMonth() + 1;
        const day = d.getDate();
        const hour = d.getHours().toString().padStart(2, '0');
        const minute = d.getMinutes().toString().padStart(2, '0');
        const second = d.getSeconds().toString().padStart(2, '0');
        return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
      },

      /** 查询申请更换部门审批列表 */
      getList() {
        this.loading = true;
        listApply(this.queryParams).then(response => {
          this.applyList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
                        id: null,
                        userId: null,
                        currentDeptId: null,
                        currentDeptName: null,
                        targetDeptId: null,
                        targetDeptName: null,
                        applyTime: null,
                        approvalTime: null,
                        approverId: null,
                        status: null,
                        applyReason: null,
                        createBy: null,
                        createTime: null,
                        updateBy: null,
                        updateTime: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加申请更换部门审批";
      },
        getStatusText(status) {
            const statusMap = {
                0: '申请中',
                1: '待审核',
                2: '审核通过',
                3: '审核驳回'
            }
            return statusMap[status] || '未知状态'
        },
        getStatusType(status) {
            const typeMap = {
                0: 'warning',
                1: 'info',
                2: 'success',
                3: 'danger'
            }
            return typeMap[status] || 'default'
        },
        /** 修改按钮操作 */
        handleUpdate(row,type) {
            this.form = copyObj(row)
            this.form.status = type

            // 如果是驳回操作，弹出输入驳回原因的对话框
            if (type === 3) {
                this.$prompt('请输入驳回原因', '驳回申请', {
                    confirmButtonText: '确定', cancelButtonText: '取消',
                    inputType: 'textarea', inputPlaceholder: '请详细说明驳回原因', inputValidator: (value) => {
                        if (!value || !value.trim()) {
                            return '驳回原因不能为空';
                        }
                        return true;
                    }
                }).then(({ value }) => {
                    this.form.reasonsRejection = value.trim();
                    this.submitUpdate();
                }).catch(() => {
                    // 取消驳回操作
                    this.$message('已取消驳回操作');
                });
            } else if (type === 2) {
                // 对于通过操作，添加二次确认弹窗
                this.$confirm('确定要通过该申请吗？', '操作确认', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.submitUpdate();
                }).catch(() => {
                    // 取消通过操作
                    this.$message('已取消通过操作');
                });
            } else {
                // 其他操作直接提交
                this.submitUpdate();
            }
        },

        // 提交更新
        submitUpdate() {
            updateApply(this.form).then(response => {
                this.$modal.msgSuccess("操作成功");
                this.getList();
            }).catch(error => {
                console.error('操作失败:', error);
                this.$message.error('操作失败，请稍后重试');
            });
        },

        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$modal.confirm('是否确认删除申请更换部门审批编号为"' + ids + '"的数据项？').then(() => {
                delApply(ids).then(response => {
                    this.$modal.msgSuccess("删除申请记录成功");
                    this.getList();
                })
            }).catch(() => {
                // 取消删除操作
                this.$modal.msg("取消删除");
            });
        },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateApply(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addApply(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
  /** 导出按钮操作 */
  handleExport() {
    this.download('system/apply/export', {
      ...this.queryParams
    }, `apply_${new Date().getTime()}.xlsx`)
  }
  }
  };
</script>
